import { defineStore  } from 'pinia'
import { login ,getProfile ,getProfileById } from '@/api/user'
import { getToken ,setToken, removeToken } from '@/utils/auth'
import { resetRoute } from '@/router'
// useStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id

const state=() => {
  return {
    token: getToken() || '',
    useInfo :<RootObjectProfile |null>{} ,
  }
}
//const getDefaultState =state()


export const useStore = defineStore('user', {
  // other options...
  state,
  getters:{
    // name():string |undefined{
    //   return this.useInfo?.username
    // },
    name:(state) => state.useInfo?.username,
    userId :(state) => state.useInfo?.userId,
    photo: (state) => state.useInfo?.staffPhoto,
  },
  actions:{
    //发送登录请求
    async login(userInfo:loginParams) {
      try {
        const res = await login(userInfo)
        console.log('登录',res)
        //设置token
        this.token=res.data
        //把token储存在cookies中
        setToken(this.token)
      } catch (error) {
        console.log(error)
      }
    },
    //获取用户的基本情况
    async loadProfile() {
      try {
        const res= await getProfile() 
        console.log('获取用户信息',res)
        const info = await this.loadProfileById(res.data.userId)
        console.log('根据id获取用户详情',info)
        //this.useInfo=(res as RootObject).data
        this.useInfo={ ...res.data,...info?.data }
        //console.log(JSON.stringify(this.useInfo))
        return res.data.roles.menus
      } catch (error) {
        console.log(error)
      }
    },
    //根据用户的id获取详细的信息
    async loadProfileById(id:string) {
      try {
        return  await getProfileById(id)
      } catch (error) {
        console.log(error)
      }
    },

    //退出
    loginOUt (){
      this.token='',
      this.useInfo=null
      removeToken()
      resetRoute()
    },
  },
})